package cn.arikeky.pet.service.impl;
import cn.arikeky.pet.domain.PetType;
import cn.arikeky.pet.mapper.PetTypeMapper;
import cn.arikeky.pet.service.IPetTypeService;
import cn.arikeky.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author arikeky
 * @since 2022-10-28
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
   
    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> batchTree() {
        List<PetType> allPetTypes = petTypeMapper.findAll();
        // stream 流
        Map<Long, PetType> parentMap = allPetTypes.stream().collect(Collectors.toMap(PetType::getId, e -> e));

        List<PetType> result = new ArrayList<>();

        for (PetType petType : allPetTypes){
            if (null == petType.getPid()){
                result.add(petType);
            } else {
                PetType parent = parentMap.get(petType.getPid());
                if (null == parent){
                    break;
                }
                parent.getChildren().add(petType);
            }
        }
        return result;

    }
}
